<?php

declare(strict_types=1);

namespace Core\Middleware\Http;

use Hyperf\Context\Context;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

/**
 * HTTP请求跨域中间件
 * Class CorsMiddleware
 */
class CorsMiddleware implements MiddlewareInterface
{

    protected array $headers = [
        'DNT',
        'Keep-Alive',
        'User-Agent',
        'Cache-Control',
        'Content-Type',
        'Authorization',
        'Auth-Token',
        'CHECK'
    ];

    /**
     * @param ServerRequestInterface $request
     * @param RequestHandlerInterface $handler
     * @return ResponseInterface
     * @author 竹林风@875384189 2021/2/26 17:04
     */
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $response = Context::get(ResponseInterface::class);
        $response = $response->withHeader('Access-Control-Allow-Origin', '*')->withHeader('Access-Control-Allow-Credentials', 'true')->withHeader('Access-Control-Allow-Headers', implode(',', $this->headers));
        Context::set(ResponseInterface::class, $response);
        if ($request->getMethod() == 'OPTIONS') {
            return $response;
        }
        return $handler->handle($request);
    }

}